﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using MKAdminCore.DTO.Web.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MKAdminCore.Filters
{
    public class MvcAuthorize : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException(nameof(filterContext));
            }
            var actionDescriptor = filterContext.ActionDescriptor;

            //允许匿名访问
            if (actionDescriptor.EndpointMetadata.Any(q => q is AllowAnonymousAttribute))
            {
                return;
            }

            //未登录用户直接跳转到登录页
            //var claimsQuery = HttpContext.User.Claims;
            //var claimsInfo = claimsQuery.Where(q => q.Type == "UserInfo").FirstOrDefault();

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                RedirectRouteUrl(filterContext);
                //filterContext.Result = new RedirectResult("/login");
                return;
            }

            //    var curUser = CurrentUser.GetLoginInfo();
            //    var request = context.HttpContext.Request;

            //    // 没有登录跳转到登录页面
            //    if (null == curUser || curUser.OperatorId <= 0)
            //    {
            //        RedirectRouteUrl(context, "100000");
            //        return;
            //    }
            //    else
            //    {
            //        string areaName = context.RouteData.DataTokens["area"] == null ? "" : context.RouteData.DataTokens["area"].ToString();
            //        string controllerName = context.ActionDescriptor.ControllerDescriptor.ControllerName;
            //        string actionName = context.ActionDescriptor.ActionName;

            //        string resourceName = $"{areaName}/{controllerName}/{actionName}";
            //        //获取功能权限
            //        if (!string.IsNullOrEmpty(areaName))
            //        {
            //            var loginService = IOCFactory.GetService<ILoginService>();
            //            //判断当前用户是否正常
            //            if (loginService.VerifyUserStatus(curUser).status)
            //            {
            //                var permissionSetting = IOCFactory.GetService<IPermissionSettingService>();
            //                var result = permissionSetting.UserPermissionVerify(resourceName, curUser);
            //                if (!result.data)
            //                {
            //                    RedirectRouteUrl(context, "100001");
            //                }
            //            }
            //            else
            //            {
            //                //退出登录
            //                Loginer.SignOut();
            //                context.Result = new RedirectResult("/login");
            //                return;
            //            }
            //        }
            //    }
        }

        private static void RedirectRouteUrl(AuthorizationFilterContext filterContext, string errMsg = "")
        {
            // 在跳转之前做判断,防止重复
            //if (filterContext.HttpContext.Response.IsRequestBeingRedirected) return;

            //判断是否为子操作或ajax请求if (context.IsChildAction || context.HttpContext.Request.IsAjaxRequest())
            bool isAjaxCall = filterContext.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
            if (isAjaxCall)
            {
                var responseResult = new HttpResponseResult { Code = (int)HttpResponseCode.Unauthorized, Msg = errMsg };
                filterContext.Result = new JsonResult(new { Data = responseResult });
            }
            else
            {
                filterContext.Result = new RedirectResult("/login");
            }
        }
    }
}
